//
//  smcJaikuHTML.m
//  juhu
//
//  Created by Christian Martick on 26.07.07.
//  Copyright 2007 Christian Martick. All rights reserved.
//
//	This object creates a webArchive from jaiku data
//
//	Copyright (C) 2007 Christian Martick, http://juhu-mac.blogspot.com
//
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.

#import "smcJaikuHTML.h"

@implementation smcJaikuHTML
+ (WebArchive *) webArchiveWithJaikuAPIObject: (smcJaikuAPI *) jaiku forStream: (NSString *) stream hideChannels: (BOOL) channelFlag 
	collapsed: (NSSet*) collapsedIDs expanded: (NSSet *) expandedIDs;
{
	// put everything into one nice webarchive
	
	NSArray *result = [jaiku stream: stream];

	NSMutableArray *resArray = [NSMutableArray arrayWithCapacity: 100];
	NSMutableString *entry = nil;
	NSMutableString *entriesHtml = [[NSMutableString alloc] init];
	NSString *tmpResourceName = nil;
	NSString *tmpToolTip = nil;
	NSString *varHREF = nil;
	BOOL canDelete = YES;
	
	// get entry template from bundle resources
	NSString *entryTemplate = [NSString stringWithContentsOfFile: 
		[NSString stringWithFormat: @"%@/%@", [[NSBundle mainBundle] resourcePath], @"entry"]];
	
	// process each entry
	for (int i = 0; i< [result count]; i++)
	{

		entry = [NSMutableString stringWithString: entryTemplate];
		canDelete = YES;
		
		//footprint
		NSString *title = [NSString stringWithFormat: @"<p class=\"title\">%@ <em>%@</em></p>", 
			[[result objectAtIndex: i] objectForKey: kSmcEntryKeyFirstName],
			[[result objectAtIndex: i] objectForKey: kSmcEntryKeyRelativeDateString]];
			 
		[entry replaceOccurrencesOfString: @"?!smallFootContent!?"
				withString: [NSString stringWithFormat: @"%@<p>%@</p>", title, [[result objectAtIndex: i] objectForKey: kSmcEntryKeyTitle]]
				options: 0 range: NSMakeRange (0, [entry length])];
		
		//depending on preferences, show in small or expanded mode as default, 
		//but first check if current one is in collapsed/expanded items (saved)
		NSString *tmpT = nil;
		if ([collapsedIDs containsObject: [[result objectAtIndex: i] objectForKey: kSmcEntryKeyID]])
			tmpT = @"";
		else if ([expandedIDs containsObject: [[result objectAtIndex: i] objectForKey: kSmcEntryKeyID]])
			tmpT = @"Clicked";
		else
			if ([[NSUserDefaults standardUserDefaults] boolForKey: @"smallFootprint"])
				tmpT = @"";
			else
				tmpT = @"Clicked";
		//do actual replacement
		[entry replaceOccurrencesOfString: @"?!entryType!?"
			withString: tmpT
			options: 0 range: NSMakeRange (0, [entry length])];
		
		//disabled
		//display or not?
		//hide channels if flag
		if (channelFlag && [[[result objectAtIndex: i] objectForKey: kSmcEntryKeyChannelFlag] boolValue])
			[entry replaceOccurrencesOfString: @"?!hideThisOne!?"
				withString: @"style=\"display:none\""
				options: 0 range: NSMakeRange (0, [entry length])];
		else
			[entry replaceOccurrencesOfString: @"?!hideThisOne!?"
				withString: @""
				options: 0 range: NSMakeRange (0, [entry length])];
				
		//post index
		[entry replaceOccurrencesOfString: @"?!index!?"
			withString: [NSString stringWithFormat: @"%i", i]
			options: 0 range: NSMakeRange (0, [entry length])];
		
		//put in user url
		[entry replaceOccurrencesOfString: @"?!user_url!?"
			withString: [[[result objectAtIndex: i] objectForKey: kSmcEntryKeyUserURL] absoluteString]
			options: NSBackwardsSearch range: NSMakeRange (0, [entry length])];
			
		//image src
		[entry replaceOccurrencesOfString: @"?!image_src!?"
			withString: [NSString stringWithFormat: @"applewebdata://juhu/x-in-memory-image:%@",
					[[[result objectAtIndex: i] objectForKey: kSmcEntryKeyUserImageURL] path]] 
			options: NSBackwardsSearch range: NSMakeRange (0, [entry length])];
				
		//buttons
		[entry replaceOccurrencesOfString: @"?!page_url!?"
			withString: [[[result objectAtIndex: i] objectForKey: kSmcEntryKeyURL] absoluteString]
			options: NSBackwardsSearch range: NSMakeRange (0, [entry length])];
		
		[entry replaceOccurrencesOfString: @"?!page_guid!?"
			withString: [NSString stringWithFormat: @":%i/%@?",i,[[result objectAtIndex: i] objectForKey: kSmcEntryKeyID]]
			options: NSBackwardsSearch range: NSMakeRange (0, [entry length])];
		
		[entry replaceOccurrencesOfString: @"?!nick!?"
			withString: [[result objectAtIndex: i] objectForKey: kSmcEntryKeyNick]
			options: NSBackwardsSearch range: NSMakeRange (0, [entry length])];
		
		// the third button: add or remove contact if not own post
		// if: show delete post but only if deletable
		if ([[[result objectAtIndex: i] objectForKey: kSmcEntryKeyNick] isEqualToString: [jaiku username]])
		{
			// own post
			varHREF = [NSString stringWithFormat: @"deletePost/%@", [[[result objectAtIndex: i] objectForKey: kSmcEntryKeyURL] absoluteString]];
			tmpResourceName = @"deletePost";
			tmpToolTip = @"delete this one";
			
			// can delete it?
			if (![jaiku canDelete: [[result objectAtIndex: i] objectForKey: kSmcEntryKeyURL]])
				canDelete = NO;
		} 
		else if ([jaiku isFriend: [[result objectAtIndex: i] objectForKey: kSmcEntryKeyNick]])
		{
			// remove from contacts
			varHREF = [NSString stringWithFormat: @"removeContact:%i/%@", i, [[result objectAtIndex: i] objectForKey: kSmcEntryKeyNick]];
			tmpResourceName = @"contactRemove";
			tmpToolTip = @"remove from contacts";
		} else
		{
			// add user in all other cases
			varHREF = [NSString stringWithFormat: @"addContact:%i/%@", i, [[result objectAtIndex: i] objectForKey: kSmcEntryKeyNick]];
			tmpResourceName = @"contactAdd";
			tmpToolTip = @"add to contacts";
		}
		
		if (canDelete)
		{
			// show third button
			[entry replaceOccurrencesOfString: @"<!--"
				withString: @""
				options: NSBackwardsSearch range: NSMakeRange (0, [entry length])];
			[entry replaceOccurrencesOfString: @"-->"
				withString: @""
				options: NSBackwardsSearch range: NSMakeRange (0, [entry length])];
		}
		
		[entry replaceOccurrencesOfString: @"?!var!?"
			withString: varHREF
			options: NSBackwardsSearch range: NSMakeRange (0, [entry length])];
		
		[entry replaceOccurrencesOfString: @"?!resource!?"
			withString: tmpResourceName
			options: NSBackwardsSearch range: NSMakeRange (0, [entry length])];
		
		[entry replaceOccurrencesOfString: @"?!tooltip!?"
			withString: tmpToolTip
			options: NSBackwardsSearch range: NSMakeRange (0, [entry length])];
		
		//put in actual post
		
		[entry replaceOccurrencesOfString: @"?!content!?"
			withString: [NSString stringWithFormat: @"<div class=\"postContent\">%@</div>", [[result objectAtIndex: i] objectForKey: kSmcEntryKeyText]]
			options: NSBackwardsSearch range: NSMakeRange (0, [entry length])];
		
		//add to entries
		[entriesHtml appendString: entry];
		
		//add user image to resource array
		
		[resArray addObject: [[[WebResource alloc] initWithData: [[jaiku getImageForUser: [[result objectAtIndex: i] objectForKey: kSmcEntryKeyNick]] TIFFRepresentation]
															URL: [NSURL URLWithString: 
																	[NSString stringWithFormat: @"applewebdata://juhu/x-in-memory-image:%@",
																		[[[result objectAtIndex: i] objectForKey: kSmcEntryKeyUserImageURL] path]]]
													   MIMEType:@"image/tiff"
											   textEncodingName:nil
													  frameName:nil] autorelease]];
	}
	
	//add button images to resources
	[resArray addObject: [[[WebResource alloc] initWithData:[[NSImage imageNamed: @"icon_expand"] TIFFRepresentation] 
                                                     URL: [NSURL URLWithString: @"applewebdata://juhu/x-in-memory-image:expand"]
                                                MIMEType:@"image/tiff"
                                        textEncodingName:nil
                                               frameName:nil] autorelease]];
											   
	[resArray addObject: [[[WebResource alloc] initWithData:[[NSImage imageNamed: @"icon_collapse"] TIFFRepresentation] 
                                                     URL: [NSURL URLWithString: @"applewebdata://juhu/x-in-memory-image:collapse"]
                                                MIMEType:@"image/tiff"
                                        textEncodingName:nil
                                               frameName:nil] autorelease]];
											   
	[resArray addObject: [[[WebResource alloc] initWithData:[[NSImage imageNamed: @"icon_homedark"] TIFFRepresentation] 
                                                     URL: [NSURL URLWithString: @"applewebdata://juhu/x-in-memory-image:home"]
                                                MIMEType:@"image/tiff"
                                        textEncodingName:nil
                                               frameName:nil] autorelease]];
											   
	[resArray addObject: [[[WebResource alloc] initWithData:[[NSImage imageNamed: @"icon_comment"] TIFFRepresentation] 
                                                     URL: [NSURL URLWithString: @"applewebdata://juhu/x-in-memory-image:comment"]
                                                MIMEType:@"image/tiff"
                                        textEncodingName:nil
                                               frameName:nil] autorelease]];
	
	[resArray addObject: [[[WebResource alloc] initWithData:[[NSImage imageNamed: @"icon_contactAdd"] TIFFRepresentation] 
                                                     URL: [NSURL URLWithString: @"applewebdata://juhu/x-in-memory-image:contactAdd"]
                                                MIMEType:@"image/tiff"
                                        textEncodingName:nil
                                               frameName:nil] autorelease]];
						   
	[resArray addObject: [[[WebResource alloc] initWithData:[[NSImage imageNamed: @"icon_contactRemove"] TIFFRepresentation] 
                                                     URL: [NSURL URLWithString: @"applewebdata://juhu/x-in-memory-image:contactRemove"]
                                                MIMEType:@"image/tiff"
                                        textEncodingName:nil
												frameName:nil] autorelease]];
	
	[resArray addObject: [[[WebResource alloc] initWithData:[[NSImage imageNamed: @"icon_trash"] TIFFRepresentation] 
                                                     URL: [NSURL URLWithString: @"applewebdata://juhu/x-in-memory-image:deletePost"]
                                                MIMEType:@"image/tiff"
                                        textEncodingName:nil
												frameName:nil] autorelease]];
	
	// add stylesheet
	[resArray addObject: [[[WebResource alloc] initWithData:[[NSString stringWithContentsOfFile: 
		[NSString stringWithFormat: @"%@/%@", [[NSBundle mainBundle] resourcePath], @"styles"]] dataUsingEncoding: NSUnicodeStringEncoding] 
                                                     URL: [NSURL URLWithString: @"applewebdata://juhu/x-in-memory-text:style"]
                                                MIMEType:@"text/css"
                                        textEncodingName:nil
												frameName:nil] autorelease]];
	
	// get html template
	NSMutableString *htmlDoc = [NSMutableString stringWithContentsOfFile: 
		[NSString stringWithFormat: @"%@/%@", [[NSBundle mainBundle] resourcePath], @"base"]];
	
	// put entries in it
	[htmlDoc replaceOccurrencesOfString: @"?!entries!?" 
		withString: entriesHtml options: NSBackwardsSearch range: NSMakeRange (0, [htmlDoc length])];

	//make webarchive
	WebResource *main = [[[WebResource alloc] initWithData: [htmlDoc dataUsingEncoding: NSUnicodeStringEncoding]
		URL: [NSURL URLWithString: @"applewebdata://juhu"] MIMEType: @"text/html" textEncodingName: @"UTF-16" frameName:nil] autorelease];
	
	[entriesHtml release];
	
	// done
	return [[[WebArchive alloc] initWithMainResource: main
		subresources: resArray subframeArchives:nil] autorelease];
	
}

+ (NSString *) loadingPage
{
	//return html string for loading page
	NSMutableString *htmlDoc = [NSMutableString stringWithContentsOfFile: 
		[NSString stringWithFormat: @"%@/%@", [[NSBundle mainBundle] resourcePath], @"fill"]];
	
	NSString *imagePath = [NSString stringWithFormat: @"file://%@/%@", [[NSBundle mainBundle] resourcePath], @"progress.gif"];
	
	[htmlDoc replaceOccurrencesOfString: @"?!imagesrc!?" 
		withString: imagePath options: NSBackwardsSearch range: NSMakeRange (0, [htmlDoc length])];
	[htmlDoc replaceOccurrencesOfString: @"?!title!?" 
		withString: @"Please wait" options: NSBackwardsSearch range: NSMakeRange (0, [htmlDoc length])];
	[htmlDoc replaceOccurrencesOfString: @"?!text!?" 
		withString: @"loading jaiku streams" options: NSBackwardsSearch range: NSMakeRange (0, [htmlDoc length])];
	
	return [NSString stringWithString: htmlDoc];
}

+ (NSString *) errorPage
{
	//return html string for error page
	NSMutableString *htmlDoc = [NSMutableString stringWithContentsOfFile: 
		[NSString stringWithFormat: @"%@/%@", [[NSBundle mainBundle] resourcePath], @"fill"]];
	
	NSString *imagePath = [NSString stringWithFormat: @"file://%@/%@", [[NSBundle mainBundle] resourcePath], @"oh.png"];
	
	[htmlDoc replaceOccurrencesOfString: @"?!imagesrc!?" 
		withString: imagePath options: NSBackwardsSearch range: NSMakeRange (0, [htmlDoc length])];
	[htmlDoc replaceOccurrencesOfString: @"?!title!?" 
		withString: @"No connection" options: NSBackwardsSearch range: NSMakeRange (0, [htmlDoc length])];
	[htmlDoc replaceOccurrencesOfString: @"?!text!?" 
		withString: @"could not download streams" options: NSBackwardsSearch range: NSMakeRange (0, [htmlDoc length])];
	
	return [NSString stringWithString: htmlDoc];
}

@end
